<?php

namespace App\Containers\AppSection\Profile\Tasks;

use App\Containers\AppSection\Profile\Data\Repositories\ProfileRepository;
use App\Ship\Criterias\ThisUserCriteria;
use App\Ship\Parents\Tasks\Task;

class GetAllProfilesTask extends Task
{
    protected ProfileRepository $repository;

    public function __construct(ProfileRepository $repository)
    {
        $this->repository = $repository;
    }

    public function run()
    {
        return $this->repository->paginate();
    }

    public function thisUser($userId): self
    {
        $this->repository->pushCriteria(new ThisUserCriteria($userId));
        return $this;
    }

    public function outerProfiles(): self
    {
        $this->repository->whereHas('user.roles', function ($query) {
            $query->whereIn('roles.name', ['borrower', 'investor']);
        });

        return $this;
    }

    public function fromRole($role): self
    {
        if (!empty($role)) {
            $this->repository->whereHas('user.roles', function ($query) use ($role) {
                $query->where('roles.name', $role);
            });
        }

        return $this;
    }

    public function whereFio($fio): self
    {
        if (!empty($fio)) {
            $this->repository
                ->whereHas('legal_form.personal', function ($query) use ($fio) {
                    $query->where('fio', 'LIKE', '%' . $fio . '%');
                })
                ->orWhereHas('legal_form.company', function ($query) use ($fio) {
                    $query->where('name', 'LIKE', '%' . $fio . '%');
                });
        }

        return $this;
    }
}
